package com.young.core.dao.impl;

import com.young.core.dao.BaseDao;
import com.young.core.dao.NodeDao;
import com.young.core.domain.NodeDO;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class NodeDaoImpl extends BaseDao implements NodeDao {

    @Override
    public void insert(NodeDO node) {
        this.sqlSession.insert("NodeMapper.insert", node);
    }

    @Override
    public int update(NodeDO node) {
        return this.sqlSession.update("NodeMapper.update", node);
    }

    @Override
    public NodeDO getSpecific(String instanceId) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("instanceId", instanceId);
        return this.sqlSession.selectOne("NodeMapper.getSpecific", parameters);
    }

    @Override
    public NodeDO getSpecific(String project, String ip, int port) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("project", project);
        parameters.put("ip", ip);
        parameters.put("port", port);
        return this.sqlSession.selectOne("NodeMapper.getSpecific", parameters);
    }

    @Override
    public Collection<NodeDO> getAll(String project) {
        return getAlive(project, -1);
    }

    @Override
    public List<NodeDO> getAlive(String project, int ttl) {
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("project", project);
        if (ttl > 0) {
            parameters.put("ttl", ttl);
        }
        return this.sqlSession.selectList("NodeMapper.getAll", parameters);
    }

    @Override
    public int expire(long ttl) {
        return this.sqlSession.delete("NodeMapper.deleteExpired", ttl);
    }

    @Override
    public int delete(int id) {
        return this.sqlSession.delete("NodeMapper.deleteById", id);
    }

    @Override
    public int delete(String instanceId) {
        return this.sqlSession.delete("NodeMapper.deleteByInstanceId", instanceId);
    }
}
